package me.iwf.photopicker.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import me.iwf.photopicker.R;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by donglua on 2016/10/19.
 */

public class PermissionsUtils {

    private static final int SETTINGS_REQUEST_CODE = 2;

    public static boolean checkReadStoragePermission(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            return true;
        }
        int readStoragePermissionState =
                ContextCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE);

        boolean readStoragePermissionGranted = readStoragePermissionState == PackageManager.PERMISSION_GRANTED;

        if (!readStoragePermissionGranted) {
            ActivityCompat.requestPermissions(activity,
                    PermissionsConstant.PERMISSIONS_EXTERNAL_READ,
                    PermissionsConstant.REQUEST_EXTERNAL_READ);
        }
        return readStoragePermissionGranted;
    }

    public static boolean checkWriteStoragePermission(Fragment fragment) {

        int writeStoragePermissionState =
                ContextCompat.checkSelfPermission(fragment.getContext(), WRITE_EXTERNAL_STORAGE);

        boolean writeStoragePermissionGranted = writeStoragePermissionState == PackageManager.PERMISSION_GRANTED;

        if (!writeStoragePermissionGranted) {
            fragment.requestPermissions(PermissionsConstant.PERMISSIONS_EXTERNAL_WRITE,
                    PermissionsConstant.REQUEST_EXTERNAL_WRITE);
        }
        return writeStoragePermissionGranted;
    }

//    /***
//     * 用户关闭并不再提醒所有权限提示* @param activity* @param permissions* @return
//     */
//    private static boolean hasDelayAllPermissions(Activity activity, String... permissions) {
//        int count = 0;
//        for (String permission : permissions) {
//            if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
//                    && ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_DENIED) {
//                count++;
//            }
//        }
//        if (count == permissions.length) {
//            return true;
//        }
//        return false;
//    }

    public static boolean checkCameraPermission(final Fragment fragment) {
        int cameraPermissionState = ContextCompat.checkSelfPermission(fragment.getContext(), CAMERA);

        boolean cameraPermissionGranted = cameraPermissionState == PackageManager.PERMISSION_GRANTED;
        boolean permissionRationale = fragment.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA);
        Log.e("TAG", "权限：" + cameraPermissionGranted);
        Log.e("TAG", "永久权限：" + permissionRationale);
        SharedPreferences sp = fragment.getActivity().getSharedPreferences("Permission", Context.MODE_PRIVATE);
        boolean isCamerraFrist = sp.getBoolean("isCamerraFrist", true);
        if (!cameraPermissionGranted) {
            fragment.requestPermissions(PermissionsConstant.PERMISSIONS_CAMERA,
                    PermissionsConstant.REQUEST_CAMERA);

        }
        if (!isCamerraFrist && !permissionRationale && !cameraPermissionGranted) {
            new AlertDialog.Builder(fragment.getActivity())
                    .setTitle(fragment.getActivity().getString(R.string.__picker_title_settings_dialog))
                    .setMessage(fragment.getActivity().getString(R.string.__picker_rationale_ask_again))
                    .setPositiveButton(fragment.getActivity().getString(R.string.__picker_setting), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", fragment.getActivity().getPackageName(), null);
                            intent.setData(uri);
//            // Start for result

                            fragment.startActivityForResult(intent, SETTINGS_REQUEST_CODE);
//                          startForResult(activityOrFragment, intent, settingsRequestCode);
                        }
                    })
                    .setNegativeButton(fragment.getString(R.string.__picker_cancel), null)
                    .show();
        }
        isCamerraFrist = false;
        sp.edit().putBoolean("isCamerraFrist", isCamerraFrist).commit();
        return cameraPermissionGranted;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean checkCameraPermission(final Activity activity) {
        int cameraPermissionState = ContextCompat.checkSelfPermission(activity, CAMERA);

        boolean cameraPermissionGranted = cameraPermissionState == PackageManager.PERMISSION_GRANTED;
        boolean permissionRationale = activity.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA);
        Log.e("TAG", "权限：" + cameraPermissionGranted);
        Log.e("TAG", "永久权限：" + permissionRationale);
        SharedPreferences sp = activity.getSharedPreferences("Permission", Context.MODE_PRIVATE);
        boolean isCamerraFrist = sp.getBoolean("isCamerraFrist", true);
        if (!cameraPermissionGranted) {
            activity.requestPermissions(PermissionsConstant.PERMISSIONS_CAMERA,
                    PermissionsConstant.REQUEST_CAMERA);

        }
        if (!isCamerraFrist && !permissionRationale && !cameraPermissionGranted) {
            new AlertDialog.Builder(activity)
                    .setTitle(activity.getString(R.string.__picker_title_settings_dialog))
                    .setMessage(activity.getString(R.string.__picker_rationale_ask_again))
                    .setPositiveButton(activity.getString(R.string.__picker_setting), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                            intent.setData(uri);
//            // Start for result

                            activity.startActivityForResult(intent, SETTINGS_REQUEST_CODE);
//                          startForResult(activityOrFragment, intent, settingsRequestCode);
                        }
                    })
                    .setNegativeButton(activity.getString(R.string.__picker_cancel), null)
                    .show();
        }
        isCamerraFrist = false;
        sp.edit().putBoolean("isCamerraFrist", isCamerraFrist).commit();
        return cameraPermissionGranted;
    }
}
